package com.sys.gradepaysys.controller;

import com.sys.gradepaysys.model.Admin;
import com.sys.gradepaysys.model.ResultData;
import com.sys.gradepaysys.model.Student;
import com.sys.gradepaysys.service.AdminService;
import com.sys.gradepaysys.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:登录与注册
 */
@Controller
@Slf4j
public class LoginController {
    @Autowired
    StudentService studentService;
    @Autowired
    AdminService adminService;

    @RequestMapping("/loginEvent")
    public String login(String username,
                        String password,
                        String login, String flag,Model model,HttpServletResponse response) {
        if ("back".equals(flag)) {
            return "login";
        }
        Student student = new Student();
        String s = "";
        ResultData<Student> resultData = null;
        if ("stu".equals(login)) {
            try {
                student = studentService.login(username, password);
                model.addAttribute("stu", student);
                Cookie cookie = new Cookie("sid", String.valueOf(student.getsId()));
                response.addCookie(cookie);
                return "program";
            } catch (Exception e) {
                resultData = new ResultData<>(500, e.getMessage(), null);
            }
        }
        if ("admin".equals(login)) {
            try {
                Admin admin1 = adminService.login(username, password);
                model.addAttribute("admin", admin1);
                Cookie cookie = new Cookie("aid", String.valueOf(admin1.getAid()));
                response.addCookie(cookie);
                return "addEvent";
            } catch (Exception e) {
                resultData = new ResultData<>(500, e.getMessage(), null);
            }
        }
        if (resultData!=null&&500 == resultData.getCode()) {
            model.addAttribute("LoginError", "登录失败");
            return "login";
        }
        return "login";
    }
    @RequestMapping("/loginPage")
    public String loginPage() {
        return "login";

    }
    @RequestMapping("/toProgram")
    public String toProgram() {
        return "program";

    }
    @RequestMapping("/toAddEvent")
    public String toAddEvent() {
        return "addEvent";

    }

    @RequestMapping("/toRegister")
    public ModelAndView toRegister() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("register");
        return modelAndView;

    }


    
    
}
